<?php

namespace admin\controllers;

use Yii;
use common\helpers\Pager;
use common\helpers\Checker;
use common\helpers\Uploader;
use common\models\Employment;
use common\models\EmploymentSalary;
use common\models\EmploymentAppeal;

class EmploymentController extends Controller {

    /**
     * @name showing Employment list
     * @return string
     */
    public function actionEmploymentList()
    {
        if( ! $this->isJson) {
            return $this->render('employment-list');
        }
        $param = $this->request->post();
        foreach(['get', 'lt'] as $key) {
            if($param[$key]) {
                $param[$key] = bcmul($param[$key], 100, 0);
            }
        }
        foreach(['start', 'end'] as $key) {
            if($param[$key]) {
                $param[$key] = str_replace('-', '', $param[$key]);
            }
        }
        $params['deleted_at'] = 0;
        $query = Employment::filterConditions(Employment::initCondition(['designer_id', 'employer_id', ['hires', '>=', 'get'], ['hires', '<', 'lt'], ['begin', '>=', 'start'], ['begin', '<', 'end'], 'status', 'deleted_at'], $param));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->with('employer')->with('designer')->orderBy('id desc')->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        return $this->json($data);
    }

    /**
     * @name show employment information
     * @param id int by get request
     * @return string
     */
    public function actionEmploymentView()
    {
        $employment = null;
        $employmentId = $this->request->get('id');
        if( ! $employment = Employment::canEdit($employmentId)) {
            return $this->error('无效的雇佣关系（Invalid Employment）', 'employment/employment-list');
        }
        return $this->render('employment-view', ['data' => $employment]);
    }


    /**
     * ----------bellow employment salary operate----------
     * @name showing Employment list
     * @return string
     */
    public function actionSalaryList()
    {
        if( ! $this->isJson) {
            return $this->render('salary-list');
        }
        $param = $this->request->post();
        foreach(['start', 'end'] as $key) {
            if($param[$key]) {
                $param[$key] = str_replace('-', '', $param[$key]);
            }
        }
        $param['deleted_at'] = 0;
        $query = EmploymentSalary::filterConditions(EmploymentSalary::initCondition(['designer_id', 'employer_id', ['paydate', '>=', 'start'], ['paydate', '<', 'end'], 'status', 'deleted_at'], $param));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->with('designer')->orderBy('paydate asc')->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        return $this->json($data);
    }

    /**
     * @name 薪酬结算
     * @param $id int 薪酬编号
     * @return mixed
     */
    public function actionSalarySettle()
    {
        $salaryId = $this->request->get('id');
        if( ! $salary = EmploymentSalary::canEdit($salaryId)) {
            return $this->error('无效的薪酬发放记录（Invalid Employment Salary）', 'employment/salary-list');
        }
        if( ! $this->request->IsPost) {
            return $this->render('salary-settle', ['data' => $salary]);
        }
        if($salary->success($this->request->post('remark'))) {
            return $this->success('薪酬发放记录（'.$salary->id.'）结算完毕（Settle Success）', [
                ['title' => '前往薪酬发放列表页', 'url' => 'employment/salary-list'],
                ['title' => '继续修改薪酬发放记录', 'url' => 'employment/salary-settle?id='.$salary->id]
            ]);
        }
        else {
            return $this->error('薪酬发放记录（'.$salary->id.'）设置`结算完毕`失败（Settle Failed）', 'employment/salary-settle?id='.$salary->id);
        }
    }

    /**
     * @name 关闭薪酬发放记录
     * @param $id int 薪酬编号
     * @return mixed
     */
    public function actionSalaryClose()
    {
        $salaryId = $this->request->get('id');
        if( ! $salary = EmploymentSalary::canEdit($salaryId)) {
            return $this->error('无效的薪酬发放记录（Invalid Employment Salary）', 'employment/salary-list');
        }
        if($salary->close($this->request->post('remark'))) {
            return $this->success('薪酬发放记录（'.$salary->id.'）已关闭（Close Success）', [
                ['title' => '前往薪酬发放列表页', 'url' => 'employment/salary-list'],
                ['title' => '继续修改薪酬发放记录', 'url' => 'employment/salary-settle?id='.$salary->id]
            ]);
        }
        else {
            return $this->error('薪酬发放记录（'.$salary->id.'））关闭薪酬记录失败（Close Failed）', 'employment/salary-settle?id='.$salary->id);
        }
    }


    /**
     * ----------bellow employment appeal operate----------
     * @name showing Employment Appeal list
     * @return string
     */
    public function actionAppealList()
    {
        if( ! $this->isJson) {
            return $this->render('appeal-list');
        }
        $param = $this->request->post();
        foreach(['start', 'end'] as $key) {
            if($param[$key]) {
                $param[$key] = str_replace('-', '', $param[$key]);
            }
        }
        $param['deleted_at'] = 0;
        $query = EmploymentAppeal::filterConditions(EmploymentAppeal::initCondition(['heandler', 'reason', 'designer_id', 'employer_id', ['created_at', '>=', 'start'], ['created_at', '<', 'end'], 'status', 'deleted_at'], $param));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->with('designer')->with('employer')->orderBy('id desc')->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        return $this->json($data);
    }

    /**
     * @name show employment appeal information
     * @param id int by get request
     * @return string
     */
    public function actionAppealSettle()
    {
        $appealId = $this->request->get('id');
        if( ! $appeal = EmploymentAppeal::canEdit($appealId)) {
            return $this->error('无效的申诉记录（Invalid Employment Appeal）', 'employment/appeal-list');
        }
        if( ! $this->request->IsPost) {
            return $this->render('appeal-settle', [
                'data' => $appeal,
                'uploads' => explode(',', $appeal->uploads)
            ]);
        }
        $rule = [
            'param' => [
                'image' => ['申诉资料'],
                'remark' => ['备注', ['maxlength' => 1024, 'required']],
            ],
        ];
        $params = $this->request->post();
        $checker = Checker::authentication($rule, $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->error($checker['message'], 'employment/appeal-settle?id='.$appeal->id);
        }
        if( ! empty($params['image'])) {
            $appeal->uploads = implode(',', $params['image']);
        }
        $appeal->remark = $params['remark'];
        if($appeal->save($this->request->post('remark'))) {
            return $this->success('申诉记录（'.$appeal->id.'）保存成功（Save Success）', [
                ['title' => '前往申诉列表页', 'url' => 'employment/appeal-list'],
                ['title' => '继续修改申诉记录', 'url' => 'employment/appeal-settle?id='.$appeal->id]
            ]);
        }
        else {
            return $this->error('申诉记录（'.$appeal->id.'）保存失败（Save Failed）<br>'.$appeal->errors(), 'employment/appeal-settle?id='.$appeal->id);
        }
    }

    /**
     * @name 薪酬结算
     * @param $id int 薪酬编号
     * @return mixed
     */
    public function actionAppealSuccess()
    {
        $appealId = $this->request->get('id');
        if( ! $appeal = EmploymentAppeal::canEdit($appealId)) {
            return $this->error('无效的申诉记录（Invalid Employment Appeal）', 'employment/appeal-list');
        }
        if( ! $this->request->IsPost) {
            return $this->render('appeal-settle', ['data' => $appeal]);
        }
        $rule = [
            'param' => [
                'image' => ['申诉资料'],
                'remark' => ['备注', ['maxlength' => 1024, 'required']],
            ],
        ];
        $params = $this->request->post();
        $checker = Checker::authentication($rule, $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->error($checker['message'], 'employment/appeal-settle?id='.$appeal->id);
        }
        if( ! empty($params['image'])) {
            $appeal->uploads = implode(',', $params['image']);
        }
        $appeal->remark = $params['remark'];
        if($appeal->success()) {
            return $this->success('申诉记录（'.$appeal->id.'）设置`已处理`成功（Save Success）', [
                ['title' => '前往申诉列表页', 'url' => 'employment/appeal-list'],
                ['title' => '继续修改申诉记录', 'url' => 'employment/appeal-settle?id='.$appeal->id]
            ]);
        }
        else {
            return $this->error('申诉记录（'.$appeal->id.'）设置`已处理`失败（Save Failed）', 'employment/appeal-settle?id='.$appeal->id);
        }
    }

    /**
     * @name 拒绝申诉
     * @param $id int 申诉编号
     * @return mixed
     */
    public function actionAppealRefuse()
    {
        $appealId = $this->request->get('id');
        if( ! $appeal = EmploymentAppeal::canEdit($appealId)) {
            return $this->error('无效的申诉记录（Invalid Employment Appeal）', 'employment/appeal-list');
        }
        if( ! $this->request->IsPost) {
            return $this->render('appeal-settle', ['data' => $appeal]);
        }
        $rule = [
            'param' => [
                'image' => ['申诉资料'],
                'remark' => ['备注', ['maxlength' => 1024, 'required']],
            ],
        ];
        $params = $this->request->post();
        $checker = Checker::authentication($rule, $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->error($checker['message'], 'employment/appeal-settle?id='.$appeal->id);
        }
        if( ! empty($params['image'])) {
            $appeal->uploads = implode(',', $params['image']);
        }
        $appeal->remark = $params['remark'];
        if($appeal->refuse()) {
            return $this->success('申诉记录（'.$appeal->id.'）拒绝成功（Save Success）', [
                ['title' => '前往申诉列表页', 'url' => 'employment/appeal-list'],
                ['title' => '继续修改申诉记录', 'url' => 'employment/appeal-settle?id='.$appeal->id]
            ]);
        }
        else {
            return $this->error('申诉记录（'.$appeal->id.'）拒绝失败（Save Failed）', 'employment/appeal-settle?id='.$appeal->id);
        }
    }

    /**
     * @name 受理申诉记录
     * @param $id int 薪酬编号
     * @return mixed
     */
    public function actionAppealAccept()
    {
        $appealId = $this->request->post('id');
        if( ! $appeal = EmploymentAppeal::canEdit($appealId)) {
            return $this->json('Appeal.Exists', '无效的申诉记录（Invalid Employment Appeal）');
        }
        if($appeal->accept()) {
            return $this->json(SuccessCode, '申诉记录（'.$appeal->id.'）受理成功（Accept Success）');
        }
        else {
            return $this->json('System.Error', '申诉记录（'.$appeal->id.'）受理失败（Accept Failed）');
        }
    }
    /***
     * @name 上传图片操作
     * @param $upload array files
     * @return string file path json
     */
    function actionUploadImage()
    {
        // 开始上传图片
        $configurate = require Yii::getAlias('@common/config/uploader.php');
        // 上传头像
        $uploader = (new Uploader($configurate['employmentAppeal']))->upload('upload');
        // $this->setStatus($uploader['code'], $uploader['message']);
        return $this->json($uploader);
    }
}